<?php

namespace App\Http\Controllers;

use App\Http\Requests\IndexActivityRequest;
use App\Http\Requests\StoreActivityRequest;
use App\Http\Requests\UpdateActivityRequest;
use App\Http\Resources\ActivityResource;
use App\Models\Activity;

class ActivityController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }

    /**
     * Display a listing of the resource.
     */
    public function index(IndexActivityRequest $request)
    {
        $activity = Activity::query();

        $activity->when($request->filled('name'), function ($query) use ($request) {
            $name = $request->input('name');
            return $query->where('name', 'like', "%$name%");
        });

        $data = $activity->paginate(
            $request->query('pageSize'),
            ['*'],
            'page',
            $request->query('pageNum')
        );
        $response = ActivityResource::collection($data);
        $total = $response->total(); // 获取分页信息中的总数
        return $this->success('查询成功', $response, $total);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreActivityRequest $request, Activity $activity)
    {
        $activity->fill($request->input());
        $activity->save();
        return $this->success('添加成功', $activity);
    }

    /**
     * Display the specified resource.
     */
    public function show(Activity $activity)
    {
        if (!isSuperadmin()) {
            return $this->error('暂无权限');
        }
        $data = new ActivityResource($activity);
        return $this->success('查询成功', $data);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Activity $activity)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateActivityRequest $request, Activity $activity)
    {
        $activity->fill($request->input());
        $activity->save();
        return $this->success('更新成功', $activity);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Activity $activity)
    {
        if (!isSuperadmin()) {
            return $this->error('暂无权限');
        }
        $activity->delete();
        return $this->success('删除成功', $activity);
    }
}
